const db = wx.cloud.database()
const _ = db.command
const statementCollection = db.collection('statement')

/**
 * 获取结算单列表
 * @param params 查询参数
 * @returns 结算单列表
 */
export const getStatements = async (params : any = {}) => {
	const { keyword = '', startDate = '', endDate = '', page = 1, pageSize = 10 } = params;
	let conditions = []
	try {
		// 关键词搜索（单号或流水号）
		if (keyword) {
			conditions.push(_.or([{ number: db.RegExp({ regexp: keyword }) }, { turnoverNumber: db.RegExp({ regexp: keyword }) }]));
		}
		// 日期范围筛选
		if (startDate && endDate) {
			conditions.push({ createTime: _.and([_.gte(new Date(startDate)), _.lte(new Date(endDate))]) });
		}
		// 如果没有查询条件，则查询所有
		if (conditions.length === 0) {
			conditions.push({ number: _.exists(true) });
		}
		// 分页查询
		const skip = (page - 1) * pageSize;
		const { data } = await statementCollection.where(_.and(conditions)).orderBy('createTime', 'desc').skip(skip).limit(pageSize).get();
		return data;
	} catch (error) {
		wx.showToast({ title: error.message || '获取结算单失败', icon: 'none' });
		console.error('获取结算单失败:', error);
		throw error;
	}
};

/**
 * 更新结算单
 * @param statement 结算单数据
 * @returns 更新结果
 */
export const updateStatement = async (statement : any) => {
	const { _id, ...data } = statement;
	try {
		wx.showLoading({ title: '更新中...', mask: true });
		await statementCollection.doc(_id).update({ data: { ...data, updateTime: db.serverDate() } });
		wx.hideLoading();
	} catch (error) {
		wx.hideLoading();
		wx.showToast({ title: '更新结算单失败', icon: 'none' });
		console.error('更新结算单失败:', error);
		throw error;
	}
};

/**
 * 获取结算单详情
 * @param id 结算单ID
 * @returns 结算单详情
 */
export const getStatementDetail = async (id : string) => {
	const orderDetailList = []
	const orderIds = []
	try {
		for (let i = 0; ; i += 20) {
			const { data: orders } = await db.collection('orders').field({ _id: true }).where({ statementId: id, status: _.lt(4) }).skip(i).limit(20).get()
			if (orders.length === 0) break
			orderIds.push(...orders.map(item => item._id))
			if (orders.length < 20) break
		}
		if (orderIds.length === 0) {
			return orderDetailList
		}
		for (let i = 0; ; i += 20) {
			const { data: orderDetails } = await db.collection('order_detail').where({ orderId: _.in(orderIds), status: _.eq(3) }).skip(i).limit(20).get()
			if (orderDetails.length === 0) break
			orderDetailList.push(...orderDetails)
			if (orderDetails.length < 20) break
		}
		return orderDetailList
	} catch (error) {
		wx.showToast({ title: '获取结算单详情失败', icon: 'none' });
		console.error('获取结算单详情失败:', error);
		throw error;
	}
};

/**
 * 获取结算统计数据
 * @param params 查询参数
 * @returns 统计数据
 */
// export const getStatementStats = async (params : any = {}) => {
// 	const { startDate = '', endDate = '' } = params;
// 	let where : any = {};

// 	try {
// 		// 日期范围筛选
// 		if (startDate && endDate) {
// 			where.createTime = _.and([
// 				_.gte(new Date(startDate).getTime()),
// 				_.lte(new Date(endDate).getTime())
// 			]);
// 		}

// 		// 聚合统计
// 		const res = await statementCollection
// 			.where(where)
// 			.aggregate()
// 			.group({
// 				_id: '$payMethod',
// 				totalAmount: $.sum('$amount'),
// 				totalPayAmount: $.sum('$payAmount'),
// 				count: $.sum(1)
// 			})
// 			.end();

// 		return res.list;
// 	} catch (error) {
// 		wx.showToast({ title: '获取统计数据失败', icon: 'none' });
// 		console.error('获取统计数据失败:', error);
// 		throw error;
// 	}
// };